using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using FireStarterModeller.BO;
using Habanero.Base;
using Habanero.Base.Exceptions;
using Habanero.BO;

namespace FireStarterModeller.Logic.Commands
{
    public class DeleteClassCommand : ICommand
    {
        private readonly DMClass _class;
        private DMAssembly _assembly;

        public DeleteClassCommand(DMClass dmClass)
        {
            _class = dmClass;
        }

        public void Apply()
        {

            if (_class == null) throw new HabaneroApplicationException(string.Format("Class '{0}' was not found on assembly '{1}'", _class, _assembly));

            _assembly = _class.Assembly;
            _class.MarkForDelete();
            try
            {
                _class.Save();
            }
            catch (Exception)
            {
                _class.CancelEdits();
                throw;
            }
        }

        public void Revert()
        {
            PropertyInfo isDeletedProperty = typeof(BOStatus).GetProperty("IsDeleted", BindingFlags.Public | BindingFlags.Instance);
            isDeletedProperty.SetValue(_class.Status, false, null);
            PropertyInfo isDirtyProperty = typeof(BOStatus).GetProperty("IsDirty", BindingFlags.Public | BindingFlags.Instance);
            isDirtyProperty.SetValue(_class.Status, true, null);
            PropertyInfo isNewProperty = typeof(BOStatus).GetProperty("IsNew", BindingFlags.Public | BindingFlags.Instance);
            isNewProperty.SetValue(_class.Status, true, null);

            _assembly.Classes.Add(_class);
            try
            {
                _class.Save();
            } catch (Exception)
            {
                _assembly.Classes.Remove(_class);
                throw;
            } 
        }
    }
}
